import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/screenutil_init.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:study_online/global/routes.dart';
import 'package:study_online/pages/courseStudyPage/CourseStudyViewModel.dart';
import 'package:study_online/pages/loginRegisterPage/LoginRegisterViewModel.dart';
import 'package:study_online/pages/myPage/MyViewModel.dart';
import 'package:study_online/pages/testPage/TestViewModel.dart';

import 'global/global.dart';
import 'utils/CustomAnimation.dart';
import 'package:study_online/pages/discussPage/DiscussViewModel.dart';

final GlobalKey<NavigatorState> navigatorKey = new GlobalKey<NavigatorState>();

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  SystemUiOverlayStyle uiStyle = SystemUiOverlayStyle.light;
  SystemChrome.setSystemUIOverlayStyle(uiStyle);
  EMPushConfig config = EMPushConfig()..enableAPNs('EaseIM_APNS_Product');
  var options = EMOptions(appKey: '1107210513231301#flutter');
  options.debugModel = true;
  options.pushConfig = config;
  EMClient.getInstance.init(options).then((value) => null);
  EasyLoading.instance
    ..displayDuration = const Duration(milliseconds: 1000)
    ..indicatorType = EasyLoadingIndicatorType.ring
    ..loadingStyle = EasyLoadingStyle.dark
    ..indicatorSize = 45.0
    ..radius = 10.0
    ..progressColor = Colors.yellow
    ..backgroundColor = Colors.green
    ..indicatorColor = Colors.yellow
    ..textColor = Colors.yellow
    ..maskColor = Colors.transparent
    ..userInteractions = true
    ..dismissOnTap = false
    ..maskType = EasyLoadingMaskType.custom
    ..customAnimation = CustomAnimation();
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => (LoginViewModel())),
        ChangeNotifierProvider(create: (_) => (PublishRemarkViewModel())),
        ChangeNotifierProvider(create: (_) => (PublishProblemViewModel())),
        ChangeNotifierProvider(create: (_) => (TestViewModel())),
        ChangeNotifierProvider(create: (_) => (MyViewModel())),
      ],
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  MyApp({Key key}) : super(key: key);
  SharedPreferences sp;
  List<String> _list=[
    'test','wind1','windchaser','chaser'
  ];
  List<String> _img=[
    'https://img2.baidu.com/it/u=3177778046,2679666165&fm=26&fmt=auto',
    'https://img1.baidu.com/it/u=2298832174,71113162&fm=26&fmt=auto',
    'https://img1.baidu.com/it/u=3686342212,2487941347&fm=26&fmt=auto',
    'https://img0.baidu.com/it/u=2895763284,3883839877&fm=26&fmt=auto'
  ];
  _spInit() async {
    sp = await SharedPreferences.getInstance();
    //_fetchContactsFromServer();
    for(int i=0;i<_list.length;++i)
     sp.setString(_list[i], _img[i]);
    Global.getInstance().num=_list.length;
  }

  @override
  Widget build(BuildContext context) {
    _spInit();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
    ]);
    return MaterialApp(
      navigatorKey: navigatorKey,
      builder: EasyLoading.init(),
      debugShowCheckedModeBanner: false,
      onGenerateRoute: onGenerateRoute,
    );
  }

  Future<void> _fetchContactsFromServer() async {
    try {
      List<EMContact> contacts =
          await EMClient.getInstance.contactManager.getAllContactsFromServer();
      List<String> _list = [];
      for (var contact in contacts) {
        _list.add(contact.userInfo.userId);
      }
      try {
        int expireTime = DateTime.fromMillisecondsSinceEpoch(
            3600)
            .millisecondsSinceEpoch;
       Map<String,EMUserInfo> userInfoMap = await EMClient.getInstance.userInfoManager
            .fetchUserInfoByIdWithExpireTime(_list, expireTime: expireTime);
        for(String i in _list){
          sp.setString(i, userInfoMap[i].avatarUrl);
        }
      } on EMError catch (e) {
        print('操作失败，原因是: $e');
      }
    } on EMError {
      SmartDialog.showToast('获取失败');
    } finally {

    }
  }
}
